package znbkTopicType.resContent;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lancooznbk.R;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.FlowLayout;
import com.example.lancooznbk.view.widget.TagAdapter;
import com.example.lancooznbk.view.widget.TagFlowLayout;
import com.example.lancooznbk.view.widget.TagView;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lancooControl.Control;
import lancooControl.CustomAnswerChoiceView;
import znbkTopicType.WrapBaseAdapter;
import znbkChangeZsdLearned.presenter.ZnbkSaveLearnedZsdPresenter;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperInfor.ZnbkPaperInfor;

import static znbkTestPaperBj.activity.NotePaperActivity.mEntityBj;
import static znbkTestPaperRdtz.activity.HeatPointExtensionPaperActivity.mEntityRdtz;
import static znbkTestPaperSc.activity.CollectionPaperActivity.mEntitySc;


/**
 * Created by Administrator on 2018\3\18 0018.
 */

public class ZnbkContentResStlDxAdapter extends WrapBaseAdapter{

    private LayoutInflater mInflater;
    //当前试题数量
    private int SumItem;
    //当前试题在当前试题的ID
    private int PaperID;
    private Context mContext;
    private int ModelFrom;//试卷来源

    private int tvBlack;
    private int tvBlue;
    private int tvWhite;
    private int tvGreen;
    private int tvRed;
    private int btnWhite;
    private int btnBlue;
    private int btnGreen;
    private int btnRed;

    private float mDensity;
    private int mHiddenViewMeasuredHeight;

    /*
    * 获取小题选项信息
    * */
    private int sumOption;//选项的个数
    private String SubChildAnswer;//正确答案
    private String SubChildAsk;//小题题目信息
    private String SubChildAnalyze;//答案解析
    private String GenreName;//题材名称
    private String TypeName;//题型名称
    private String NoteId;//笔记ID
    private String ResType;//资源类型

    private String[] OptionIndex;//选项号所对应的文字
    private String[] OptionContent;//选项内容对应的文字

    private View mView;

    private ViewHolder holder = null;
    private class ViewHolder{
        TextView TvItemContent;//大题文本题干
        LinearLayout LayoutOptions;//选项显示区
        LinearLayout LayoutCheckAnalysis;//答案显示区
        LinearLayout LayoutStuAnswer;
        LinearLayout LayoutAnswer;
        LinearLayout LayoutAnalysis;
        TextView TvAnswer;//正确答案
        TextView TvStuAnswer;//学生答案
        TextView TvAnalysis;//解析

        private ViewHolder(View convertView) {
            mView = convertView;
            TvItemContent = (TextView) convertView.findViewById(R.id.tv_item_content);
            LayoutOptions = (LinearLayout) convertView.findViewById(R.id.layout_options);
            LayoutCheckAnalysis= (LinearLayout) convertView.findViewById(R.id.layout_checkAnalysis);
            LayoutStuAnswer = (LinearLayout) convertView.findViewById(R.id.layout_stuAnswer);
            LayoutAnswer = (LinearLayout) convertView.findViewById(R.id.layout_answer);
            LayoutAnalysis = (LinearLayout) convertView.findViewById(R.id.layout_analysis);
            TvAnswer = (TextView) convertView.findViewById(R.id.tv_answer);
            TvStuAnswer = (TextView) convertView.findViewById(R.id.tv_stuAnswer);
            TvAnalysis = (TextView) convertView.findViewById(R.id.tv_analysis);
        }
    }

    private CustomAnswerChoiceView[] ChoiceAnswer;//选项信息


    public ZnbkContentResStlDxAdapter(Context context, int sumItem, int paperID, int modelFrom) {
        mInflater = LayoutInflater.from(context);
        this.mContext = context;
        this.SumItem = sumItem;
        this.PaperID = paperID;
        this.ModelFrom = modelFrom;

        tvBlack = mContext.getResources().getColor(R.color.black);
        tvBlue = mContext.getResources().getColor(R.color.blue);
        tvWhite = mContext.getResources().getColor(R.color.white);
        tvGreen = mContext.getResources().getColor(R.color.green);
        tvRed = mContext.getResources().getColor(R.color.red);

        btnWhite = R.mipmap.option_normal;
        btnBlue = R.mipmap.option_select;
        btnGreen = R.mipmap.option_right;
        btnRed = R.mipmap.option_wrong;

    }

    @Override
    public int getCount() {
        return SumItem;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.znbk_adapter_content_stl_dx_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        /*
        * 获取试题相关信息
        * */
        getQuesInfor();

        /*
        * 展示作答区内容及实现作答流程
        * */
        showQuesInfor();

        /*
        * 已提交状态下，初始化答案解析
        * */
        showAnalysis();


        return convertView;
    }

    /*
    * 获取试题相关信息
    * */
    private void getQuesInfor(){

        if(ModelFrom== ZnbkPaperDef.FROM_HEAT_POINT_EXTENSION) {


                /*
                * 笔记ID：NoteId --》是否有笔记内容
                * 资源类型：ResType--》哪种资源的笔记：Q为试题类，Flag=0；其他为其他类Flag = 1
                * */
                    NoteId = mEntityRdtz.getNoteId();
                    ResType = mEntityRdtz.getResFromTK().getResType();
                /*
                * 题材名称：ResTypeName
                * */
                    GenreName = mEntityRdtz.getResFromTK().getGenreName();
                /*
                * 试题类型名称：TypeName
                * */
                    TypeName = mEntityRdtz.getResFromTK().getTypeName();
                /*
                * 大题题干内容：SubChildAsk
                * */
                    SubChildAsk = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
                /*
                * 选项个数：sumOption
                * */
                    sumOption = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().size();
                /*
                * 正确答案：SubChildAnswer
                * */
                    SubChildAnswer = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildAnswer();
                /*
                * 答案解析：SubChildAnalyze
                * */
                    SubChildAnalyze = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildAnalyze();
                /*
                * 选项题号：OptionIndex[i]
                * 选项内容：OptionContent[i]
                * */
                    OptionIndex = new String[sumOption];
                    OptionContent = new String[sumOption];
                    for (int i = 0; i < sumOption; i++) {
                        OptionIndex[i] = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().get(i).getOptionIndex();
                        OptionContent[i] = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().get(i).getOptionContent();
                    }
        }else if(ModelFrom==ZnbkPaperDef.FROM_COLLECTION){

                              /*
                    * 笔记ID：NoteId --》是否有笔记内容
                    * 资源类型：ResType--》哪种资源的笔记：Q为试题类，Flag=0；其他为其他类Flag = 1
                    * */
                        NoteId = mEntitySc.getResDetail().getNoteId();
                        ResType = mEntitySc.getResDetail().getResType();
                    /*
                    * 题材名称：ResTypeName
                    * */
                        GenreName = mEntitySc.getResDetail().getGenreName();
                    /*
                    * 试题类型名称：TypeName
                    * */
                        TypeName = mEntitySc.getResDetail().getTypeName();
                    /*
                    * 大题题干内容：SubChildAsk
                    * */
                        SubChildAsk = mEntitySc.getResDetail().getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
                    /*
                    * 选项个数：sumOption
                    * */
                        sumOption = mEntitySc.getResDetail().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().size();
                    /*
                    * 正确答案：SubChildAnswer
                    * */
                        SubChildAnswer = mEntitySc.getResDetail().getChildList().get(0).getSubChildList().get(0).getSubChildAnswer();
                    /*
                    * 答案解析：SubChildAnalyze
                    * */
                        SubChildAnalyze = mEntitySc.getResDetail().getChildList().get(0).getSubChildList().get(0).getSubChildAnalyze();
                    /*
                    * 选项题号：OptionIndex[i]
                    * 选项内容：OptionContent[i]
                    * */
                        OptionIndex = new String[sumOption];
                        OptionContent = new String[sumOption];
                        for (int i = 0; i < sumOption; i++) {
                            OptionIndex[i] = mEntitySc.getResDetail().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().get(i).getOptionIndex();
                            OptionContent[i] = mEntitySc.getResDetail().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().get(i).getOptionContent();
                        }

        }else if(ModelFrom==ZnbkPaperDef.FROM_NOTE){

                                      /*
                            * 笔记ID：NoteId --》是否有笔记内容
                            * 资源类型：ResType--》哪种资源的笔记：Q为试题类，Flag=0；其他为其他类Flag = 1
                            * */
                    NoteId = mEntityBj.getModelTKQue().getNoteId();
                    ResType = mEntityBj.getModelTKQue().getResType();
                            /*
                            * 题材名称：ResTypeName
                            * */
                    GenreName = mEntityBj.getModelTKQue().getGenreName();
                            /*
                            * 试题类型名称：TypeName
                            * */
                    TypeName = mEntityBj.getModelTKQue().getTypeName();
                            /*
                            * 大题题干内容：SubChildAsk
                            * */
                    SubChildAsk = mEntityBj.getModelTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
                            /*
                            * 选项个数：sumOption
                            * */
                    sumOption = mEntityBj.getModelTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().size();
                            /*
                            * 正确答案：SubChildAnswer
                            * */
                    SubChildAnswer = mEntityBj.getModelTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildAnswer();
                            /*
                            * 答案解析：SubChildAnalyze
                            * */
                    SubChildAnalyze = mEntityBj.getModelTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildAnalyze();
                            /*
                            * 选项题号：OptionIndex[i]
                            * 选项内容：OptionContent[i]
                            * */
                    OptionIndex = new String[sumOption];
                    OptionContent = new String[sumOption];
                    for (int i = 0; i < sumOption; i++) {
                        OptionIndex[i] = mEntityBj.getModelTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().get(i).getOptionIndex();
                        OptionContent[i] = mEntityBj.getModelTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildOptionList().get(i).getOptionContent();
                    }
        }




    }


    /*
    * 展示试题信息
    * */
    Handler htmlHandlerItemContent = new Handler();
    private void showQuesInfor(){

        /*
        * 显示题目题干
        * */
        SubChildAsk = StringEscapeUtils.unescapeXml(SubChildAsk);
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                final Spanned tvItemContent = Html.fromHtml(SubChildAsk, Control.imgGetter,null);
                htmlHandlerItemContent.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        holder.TvItemContent.setText(tvItemContent);
                        holder.TvItemContent.setTextSize(18);
                    }
                });
            }
        }).start();


        /*
        * 显示选项内容
        * */
        ChoiceAnswer = new CustomAnswerChoiceView[sumOption];
        for(int i =0;i<sumOption;i++){
            ChoiceAnswer[i] = new CustomAnswerChoiceView(mContext);
            ChoiceAnswer[i].setAnswerChoice(OptionIndex[i],tvBlack,btnWhite,OptionContent[i],tvBlack);

            final int finalI = i;
            ChoiceAnswer[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    return;
                }
            });

            ChoiceAnswer[i].BtnChoice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        return;
                }
            });

            holder.LayoutOptions.addView(ChoiceAnswer[i]);

        }

        int currentTrueOption = Integer.valueOf(Control.stringToAscii(SubChildAnswer)) - 65;
        for (int k = 0; k < sumOption; k++) {
            if(currentTrueOption == k){
                ChoiceAnswer[k].setAnswerChoice(OptionIndex[k],tvWhite,btnGreen,OptionContent[k],tvGreen);
            }
        }


    }



    /*
    * 已提交状态试题分析部分内容展示
    * */
    private void showAnalysis() {

        holder.LayoutCheckAnalysis.setVisibility(View.VISIBLE);
        holder.LayoutStuAnswer.setVisibility(View.GONE);
    /*显示参考答案*/
        holder.TvAnswer.setText(SubChildAnswer);
        holder.TvAnswer.setTextColor(tvGreen);
    /*显示解析*/
        if(!SubChildAnalyze.equals("")) {
            holder.TvAnalysis.setText(SubChildAnalyze);
        }else{
            holder.TvAnalysis.setText(R.string.znbk_no_analysis);
        }
        holder.TvAnalysis.setTextColor(tvBlack);

    }


    /******************************************查看知识点学习情况****************************************************/
    PopupWindow popWinKnowledgePoint = null;
    private TagFlowLayout mFlowLayout;
    private TextView TvKnowledgePointTitle;
    public PopupWindow showKnowledgePointPopupWindow(final View anchorView, final View.OnClickListener onClickListener) {
        final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.znbk_pw_knowledge_point, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
        // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
        // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小
//        final PopupWindow popupWindow = new PopupWindow(contentView,
//                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        mFlowLayout = (TagFlowLayout) contentView.findViewById(R.id.id_flowlayout);
        TvKnowledgePointTitle = (TextView) contentView.findViewById(R.id.tv_knowledge_point_title);

        popWinKnowledgePoint = new PopupWindow(contentView,
                FrameLayout.LayoutParams.MATCH_PARENT, contentView.getMeasuredHeight(), false);

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWinKnowledgePoint.dismiss();
                popWinKnowledgePoint = null;
                onClickListener.onClick(v);
            }
        });

        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popWinKnowledgePoint, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popWinKnowledgePoint.setBackgroundDrawable(new ColorDrawable());

        // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
        popWinKnowledgePoint.setOutsideTouchable(true);

        // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
        popWinKnowledgePoint.setTouchable(true);

        // true时，点击返回键先消失 PopupWindow
        // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
        // false时PopupWindow不处理返回键
        popWinKnowledgePoint.setFocusable(false);
        popWinKnowledgePoint.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;   // 这里面拦截不到返回键
            }
        });
        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popWinKnowledgePoint.showAsDropDown(anchorView);

        initKnowledgePoint();

        return popWinKnowledgePoint;
    }

    private void autoAdjustArrowPos(PopupWindow popupWindow, View contentView, View anchorView) {
        View upArrow = contentView.findViewById(R.id.up_arrow);
        View downArrow = contentView.findViewById(R.id.down_arrow);

        int pos[] = new int[2];
        contentView.getLocationOnScreen(pos);
        int popLeftPos = pos[0];
        anchorView.getLocationOnScreen(pos);
        int anchorLeftPos = pos[0];
        int arrowLeftMargin = anchorLeftPos - popLeftPos + anchorView.getWidth() / 2 - upArrow.getWidth() / 2;
        upArrow.setVisibility(popupWindow.isAboveAnchor() ? View.INVISIBLE : View.VISIBLE);
        downArrow.setVisibility(popupWindow.isAboveAnchor() ? View.VISIBLE : View.INVISIBLE);

        RelativeLayout.LayoutParams upArrowParams = (RelativeLayout.LayoutParams) upArrow.getLayoutParams();
        upArrowParams.leftMargin = arrowLeftMargin;
        RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) downArrow.getLayoutParams();
        downArrowParams.leftMargin = arrowLeftMargin;
    }


    /******************************************获取知识点学习情况****************************************************/
    private List<String> AllTagsPosition;//整个标签存放集合
    private HashMap<Integer, Boolean> map;//记录选择的位置
    private void initKnowledgePoint(){

        AllTagsPosition = new ArrayList<>(0);
        map = new HashMap<>(0);

        int sumKnowledgePoint = mEntityRdtz.getResFromTK().getImportantZSD().size();
        for (int i = 0; i < sumKnowledgePoint; i++) {
            AllTagsPosition.add(mEntityRdtz.getResFromTK().getImportantZSD().get(i).getZSDName());
        }

        for(int i=0;i<AllTagsPosition.size();i++){
            if(!mEntityRdtz.getResFromTK().getImportantZSD().get(i).getUpdateTime().equals("")){
                map.put(i,true);
            }else{
                map.put(i,false);
            }
        }


        mFlowLayout.setAdapter(new TagAdapter<String>(AllTagsPosition.toArray(new String[AllTagsPosition.size()])) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.view_textview,mFlowLayout,false);
                tv.setText(s);
                return tv;
            }

        });//

        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                ((TagView)view).setChecked(true);

                int LeanedKnowledge2 =0;

                ZnbkPaperInfor.ZSDName = mEntityRdtz.getResFromTK().getImportantZSD().get(position).getZSDName();
                ZnbkPaperInfor.ZSDCode = mEntityRdtz.getResFromTK().getImportantZSD().get(position).getZSDCode();

                if(mEntityRdtz.getResFromTK().getImportantZSD().get(position).getUpdateTime().equals("")){

                    if(!map.get(position)) {
                        map.put(position, true);
                    }

                }

                for (int i = 0; i < AllTagsPosition.size(); i++) {
                    if (map.get(i)) {
                        ((TagView)mFlowLayout.getChildAt(i)).setChecked(true);
                        LeanedKnowledge2++;
                    }else {
                        ((TagView)mFlowLayout.getChildAt(i)).setChecked(false);
                    }
                }



                TvKnowledgePointTitle.setText(Html.fromHtml("知识点(共 "+AllTagsPosition.size()+
                        "个,已学习"+"<font color='#ff323d'><middle><middle>"+LeanedKnowledge2+"</middle></middle></font>"+"个,未学习"+
                        "<font color='#ff323d'><middle><middle>"+(AllTagsPosition.size()-LeanedKnowledge2)+"</middle></middle></font>"+"个)"));


                ZnbkSaveLearnedZsd();
//                DictionaryActicity.startWithContent(mContext,AllTagsPosition.get(position));

                return false;
            }
        });


        int LeanedKnowledge1 = 0;
        for (int i = 0; i < AllTagsPosition.size(); i++) {
            if (map.get(i)) {
                ((TagView)mFlowLayout.getChildAt(i)).setChecked(true);
                LeanedKnowledge1++;
            }else {
                ((TagView)mFlowLayout.getChildAt(i)).setChecked(false);
            }
        }

        TvKnowledgePointTitle.setText(Html.fromHtml("知识点(共 "+sumKnowledgePoint+
                "个,已学习"+"<font color='#ff323d'><middle><middle>"+LeanedKnowledge1+"</middle></middle></font>"+"个,未学习"+
                "<font color='#ff323d'><middle><middle>"+(sumKnowledgePoint-LeanedKnowledge1)+"</middle></middle></font>"+"个)"));

    }
    /*
* 保存一血知识点
* */
    ZnbkSaveLearnedZsdPresenter mZnbkSaveLearnedZsdPresenter;
    public void ZnbkSaveLearnedZsd(){
        mZnbkSaveLearnedZsdPresenter = new ZnbkSaveLearnedZsdPresenter((ILoadPaperView) mView,ModelFrom);
        mZnbkSaveLearnedZsdPresenter.getData(false);
    }

}